package com.lisen.common.base.util;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Random;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

public class StaticMethod {
	public static String method2class(Method method) {
		String methodName = method.getName();
		String clz = method.getDeclaringClass().getName();
		Class<?> paramTypes[] = method.getParameterTypes();
		String types = "";
		if (paramTypes != null && paramTypes.length > 0) {
			for (int i = 0; i < paramTypes.length; i++)
				types = types + paramTypes[i].getName() + ",";

			types = types.substring(0, types.length() - 1);
		}
		return clz + "." + methodName + "(" + types + ")";
	}

	/**
	 * 修饰一下才能满足Extjs的Json格式
	 * 
	 * @param str
	 * @return
	 */
	public static String modifyExtjsJsonModify(String str) {
		return ("[" + str + "]").replaceAll(",]", "]");
	}

	/**
	 * 如果字符串为null或者不能转换成整型，返回为0
	 * 
	 * @param s
	 * @return
	 */
	public static int null2int(String s) {
		int i = 0;
		try {
			i = Integer.parseInt(s);
		} catch (Exception e) {
			i = 0;
		}
		return i;
	}

	/**
	 * 如果字符串为null，返回为空，否则返回该字符串
	 * 
	 * @param s
	 * @return
	 */
	public static String null2String(String s) {
		String str = "";
		try {
			if (s != null) {
				str = s;
			}
		} catch (Exception e) {
			str = "";
		}
		return str;
	}

	/**
	 * 如果对象为null，返回为空串，否则返回该对象的字符串
	 * 
	 * @param s
	 * @return
	 */
	public static String nullObject2String(Object s) {
		String str = "";
		try {
			str = s.toString();
		} catch (Exception e) {
			str = "";
		}
		return str;
	}

	/**
	 * 如果对象可以转换为整型，则返回，否则返回给定的默认值
	 * 
	 * @param s
	 * @param in
	 * @return
	 */
	public static int nullObject2int(Object s, int in) {
		String str = "";
		int i = in;
		try {
			str = s.toString();
			i = Integer.parseInt(str);
		} catch (Exception e) {
			i = in;
		}
		return i;
	}

	public static int nullObject2int(Object s) {
		String str = "";
		int i = 0;
		try {
			str = s.toString();
			i = Integer.parseInt(str);
		} catch (Exception e) {
			i = 0;
		}
		return i;
	}

	/**
	 * 根据输入的格式(String _dtFormat)得到当前时间格式
	 * 
	 * @param _dtFormat
	 * @return
	 */
	public static String getCurrentDateTime(String _dtFormat) {
		String currentdatetime = "";
		try {
			Date date = new Date(System.currentTimeMillis());
			SimpleDateFormat dtFormat = new SimpleDateFormat(_dtFormat);
			currentdatetime = dtFormat.format(date);
		} catch (Exception e) {
			System.out.println("时间格式不正确");
			e.printStackTrace();
		}
		return currentdatetime;
	}

	public static void populate(Object bean, String prefix, String suffix,
			HttpServletRequest request) throws ServletException {
		// Build a list of relevant request parameters from this request
		HashMap properties = new HashMap();
		// Iterator of parameter names
		Enumeration names = null;
		names = request.getParameterNames();

		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			String stripped = name;
			if (prefix != null) {
				if (!stripped.startsWith(prefix)) {
					continue;
				}
				stripped = stripped.substring(prefix.length());
			}
			if (suffix != null) {
				if (!stripped.endsWith(suffix)) {
					continue;
				}
				stripped = stripped.substring(0, stripped.length()
						- suffix.length());
			}
			Object parameterValue = null;
			parameterValue = request.getParameterValues(name);
			if (!(stripped.startsWith("org.apache.struts."))) {
				properties.put(stripped, parameterValue);
			}
		}
		// Set the corresponding properties of our bean
		try {
			BeanUtils.populate(bean, properties);
		} catch (Exception e) {
			throw new ServletException("BeanUtils.populate", e);
		} finally {
		}
	}

	public static void populate(Object bean, HttpServletRequest request)
			throws ServletException {
		populate(bean, null, null, request);
	}

	// regex
	private static String ipRegex = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
	private static String intRegex = "\\d{1,11}";
	private static String dataRegex = "\\d{4}-{1}\\d{1,2}-{1}\\d{1,2}";
	private static String timeRegex = "\\d{1,2}:{1}\\d{1,2}:{1}\\d{1,2}";
	private static String emailRegex = "[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\\.[A-Za-z]{2,10}";
	private static String ftpRegex = "ftp://\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
	private static String httpRegex = "http://\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}:\\d{1,5}.{0,200}";
	private static String httpAllRegex = "((http://)?([a-z]+[.])|(www.))\\w+[.]([a-z]{2,4})?[[.]([a-z]{2,4})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z]{2,4}+|/?)";
	private static String CN_1 = "[\u2E80-\u9FFF]+$";// 匹配所有东亚区的语言
	private static String CN_2 = "[\u4E00-\u9FFF]+$ ";// 匹配简体和繁体
	private static String CN_3 = "[\u4E00-\u9FA5]+$";// 简体

	// ip
	public static boolean isIp(String obj) {
		if (isEmpty(obj)) {
			return false;
		} else {
			return Pattern.matches(ipRegex, obj);
		}
	}

	// int
	public static boolean isInt(String obj) {
		if (isEmpty(obj)) {
			return false;
		} else {
			return Pattern.matches(intRegex, obj);
		}
	}

	public static boolean isInt(Integer obj) {
		if (isEmpty(obj)) {
			return false;
		} else {
			return Pattern.matches(intRegex, String.valueOf(obj));
		}
	}

	// date
	public static boolean isDate(Date date) {
		String obj = format(date);
		if (obj == null) {
			return false;
		} else {
			return Pattern.matches(dataRegex, obj);
		}
	}

	// time 大于当前时间
	public static boolean isAfter(Date date, String time) {
		String obj = format(date);
		if (obj == null) {
			return false;
		}
		StringBuffer b = new StringBuffer(obj);
		b.append(" ").append(time);
		Date in = parse(b.toString());
		if (in == null) {
			return false;
		}
		String now = fullFormat(new Date());
		if (now == null) {
			return false;
		}
		Date nowDate = parse(now);
		if (in.before(nowDate)) {
			return false;
		} else {
			return true;
		}
	}

	public static boolean isBefore(Date startDate, Date endDate) {
		return startDate.before(endDate);
	}

	// time
	public static boolean isTime(String obj) {
		if (isEmpty(obj)) {
			return false;
		} else {
			return Pattern.matches(timeRegex, obj);
		}
	}

	public static boolean isEmail(String obj) {
		if (isEmpty(obj)) {
			return false;
		} else {
			return Pattern.matches(emailRegex, obj);
		}
	}

	public static String format(Date date) {
		String f = null;
		if (isEmpty(date)) {
			return null;
		}
		try {
			Format format = new SimpleDateFormat("yyyy-MM-dd");
			f = format.format(date);
		} catch (Exception e) {
			return null;
		}
		return f;
	}

	public static String fullFormat(Date date) {
		String f = null;
		if (isEmpty(date)) {
			return null;
		}
		try {
			Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			f = format.format(date);
		} catch (Exception e) {
			return null;
		}
		return f;
	}

	public static Date parse(String date) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d;
		try {
			d = format.parse(date);
		} catch (ParseException e) {
			return null;
		}
		return d;
	}

	public static boolean isEmpty(Object obj) {
		if (obj == null) {
			return true;
		} else if (obj instanceof String) {
			if ("".equals(((String) obj).trim())) {
				return true;
			}
		}
		return false;
	}

	// 获得ftp文件路径,"第一位:/,最后一位:无/"
	public static String getFtpDir(String s) {
		if (isEmpty(s)) {
			return "";
		}
		if (s.indexOf("/") != 0) {
			s = "/" + s;
		}
		if (s.lastIndexOf("/") + 1 == s.length()) {
			s = s.substring(0, s.length() - 1);
		}
		return s;
	}

	public static boolean isFtp(String s) {
		if (isEmpty(s)) {
			return false;
		}

		return Pattern.matches(ftpRegex, s);
	}

	public static boolean isHttp(String s) {
		if (isEmpty(s)) {
			return false;
		}
		return Pattern.matches(httpRegex, s);
	}

	public static boolean isAllHttp(String s) {
		if (isEmpty(s)) {
			return false;
		}
		return Pattern.matches(httpAllRegex, s);// org.apache.commons.validator.GenericValidator.isUrl(s);
	}

	public static boolean isCn(String s) {
		if (isEmpty(s)) {
			return false;
		} else {
			return Pattern.matches(CN_3, s);
		}
	}

	/**
	 * 获取随级字符串
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) {
		StringBuffer buffer = new StringBuffer(
				"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
		StringBuffer sb = new StringBuffer();
		Random r = new Random();
		int range = buffer.length();
		for (int i = 0; i < length; i++) {
			sb.append(buffer.charAt(r.nextInt(range)));
		}
		return sb.toString();
	}

	public static String upperFirstChar(String str) {
		if (isEmpty(str)) {
			return str;
		}
		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}
		for (int i = 1; i < ch.length; i++) {
			if (ch[i - 1] == 32 && (ch[i] >= 'a' && ch[i] <= 'z')) {
				ch[i] = (char) (ch[i] - 32);
			}
		}
		str = new String(ch);
		return str;
	}

	/**
	 * 四舍五入 保留 scale小数
	 * 
	 * @param d
	 * @param scale
	 * @return
	 */
	public static Double doubleFormat(Double d, int scale) {
		BigDecimal b = new BigDecimal(d);
		return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	/**
	 * 四舍五入 保留2位小数
	 * 
	 * @param d
	 * @return
	 */
	public static Double doubleFormat(Double d) {
		if (isEmpty(d)) {
			return 0.0;
		} else {
			return doubleFormat(d, 2);
		}
	}
}
